﻿using Microsoft.Extensions.DependencyInjection;
using System.Security.Authentication.ExtendedProtection;

namespace 依赖注入
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            services.AddSingleton<ITestService, TestServiceImpl>();
            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                //GetRequiredService 必须的，如果找不到，直接抛异常
                ITestService t = sp.GetRequiredService<ITestService>();
                t.Name = "Test";
                t.SayHi();

                Console.WriteLine(t.GetType());//获取实现的类型
            };
            Console.Read();
        }


        static void Main1(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            //services.AddTransient<TestServiceImpl>();//瞬态形式，每次请求都会创建一个新对象
            services.AddSingleton<TestServiceImpl>();//单例形式，全局共用一个对象
            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                TestServiceImpl t = sp.GetRequiredService<TestServiceImpl>();
                t.Name = "Test";
                t.SayHi();

                TestServiceImpl t1 = sp.GetRequiredService<TestServiceImpl>();
                Console.WriteLine(object.ReferenceEquals(t,t1));//对比
            };
            
        }
    }
}
